<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        li {
            list-style: none;
        }

        .menu {
            width: 150px;
            height: 200px;
            border: 1px solid #333;
            padding: 5px 0;
            position: fixed;
            display: none;
        }

        .menu li {
            line-height: 45px;
            font-size: 14px;
            text-indent: 20px;
        }

        .menu li:hover {
            background-color: #f3f3f3;
        }
    </style>
</head>

<body>
    <div class="menu">
        <ul>
            <li class="copy">复制</li>
            <li>粘贴</li>
            <li>剪切</li>
            <li>刷新</li>
        </ul>
    </div>
</body>
<script>
    var menu = document.getElementsByClassName("menu")[0];

    var clientWidth;
    var clientHeight;
    var maxLeft;
    var maxTop;
    window.onresize = function () {
        clientWidth = document.documentElement.clientWidth || document.body.clientWidth;
        clientHeight = document.documentElement.clientHeight || document.body.clientHeight;
        maxLeft = clientWidth - menu.clientWidth;
        maxTop = clientHeight - menu.clientHeight;
    }

    document.oncontextmenu = function (e) {
        var e = e || window.event;
        var target = e.target || srcElement;
        if (e.preventDefault) {
            e.preventDefault();
        } else {
            e.returnValue = false;
        }
        menu.style.display = "block";

        clientWidth = document.documentElement.clientWidth || document.body.clientWidth;
        clientHeight = document.documentElement.clientHeight || document.body.clientHeight;
        maxLeft = clientWidth - menu.clientWidth;
        maxTop = clientHeight - menu.clientHeight;

        // console.log(maxLeft, maxTop);
        // console.log(menu.clientWidth,menu.clientHeight);

        var x = e.clientX;
        var y = e.clientY;

        if (x < 0) x = 0;
        if (y < 0) y = 0;
        if (x > maxLeft) x = e.clientX - menu.clientWidth;
        if (y > maxTop) y = e.clientY - menu.clientHeight;
        // console.log(x, y);

        menu.style.left = x + "px";
        menu.style.top = y + "px";

    }

    menu.onclick = function (e) {
        var e = e || window.event;
        var target = e.target || srcElement;

        if (e.stopPropagation) {
            e.stopPropagation();
        } else {
            e.cancelBubble = true;
        }

        if (target.className == "copy") {
            console.log("复制");
        }
        menu.style.display = "none";
    }

    document.onclick = function () {
        menu.style.display = "none";
    }

</script>

</html>